package com.lagou.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * IP防暴刷过滤器
 * @author yzh
 * @date 2020/5/3 16:40
 */
@Component
@RefreshScope
public class IPFilter implements GlobalFilter, Ordered {

    /**
     * 请求数阈值
     */
    @Value("${maxnum}")
    private Integer maxnum;

    /**
     * 单位时间,单位为秒
     */
    @Value("${basetime}")
    private Integer basetime;

    /**
     * IP及其单位时间内的请求次数集合
     */
    private static ConcurrentHashMap<String, Integer> ipCountMap;

    /**
     * 单位时间计数,60秒为一个单位时间
     */
    private static Integer COUNT_NUM = 1;

    {
        ipCountMap = new ConcurrentHashMap<>();
        new Thread(() -> {
            try {
                while (true) {
                    if(basetime != null) {
                        Thread.sleep(basetime*1000);
                        //遍历IP及其单位时间内的请求次数集合,重置所有统计次数
                        ipCountMap.forEach((k,v) -> {
                            System.out.println("开始重置IP地址为"+k+"的统计次数,重置前次数为"+v);
                            if(v > 0) {
                                ipCountMap.put(k,0);
                            }
                            System.out.println("结束重置IP地址为"+k+"的统计次数,重置后次数为"+ipCountMap.get(k));
                        });
                        System.out.println("第"+COUNT_NUM+"个单位时间结束");
                        COUNT_NUM++;
                        System.out.println("第"+COUNT_NUM+"个单位时间开始");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().toString();
        String ip = "127.0.0.1";
        HttpHeaders headers = request.getHeaders();
        List<String> ipList = headers.get("X-Forwarded-For");
        if(ipList != null && ipList.size() > 0) {
            ip = ipList.get(0);
        }
        //调用邮件微服务的Register接口前进行过滤
        if(uri.contains("/api/user/register")) {
            //进行次数统计
            Integer count = ipCountMap.get(ip);
            if(count == null) {
                count = 0;
            } else {
                if(count == 100) {
                    //设置响应内容
                    String msg = "您频繁进⾏注册，请求已被拒绝!";
                    //设置响应状态码
                    response.setStatusCode(HttpStatus.SEE_OTHER);
                    return response.writeWith(Mono.just(response.bufferFactory().wrap(msg.getBytes())));
                }
            }
            ipCountMap.put(ip, ++count);
            System.out.println("IP地址为"+ip+"进行请求,单位时间累计请求次数为"+ipCountMap.get(ip));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
